#include <stdio.h>
#include <stdlib.h>
#include "class.h"


static void ShapeInit(Shape *this, int a, int b)
{
    this->width = a;
    this->height = b;
}

static Shape* ShapeCreate(int a, int b)
{
    Shape *shape = malloc(sizeof(Shape));
    ShapeInit(shape, a, b);
    return shape;
}

MShape mshape[1] =
{{
    ShapeCreate,
    ShapeInit,
}};

static int RectangleArea(Shape *shape)
{
    printf("Rectangle class area\n");
    return shape->width * shape->height;
}

static void RectangleInit(Rectangle *this, int a, int b)
{
    mshape->init(this->shape, a, b);
    this->shape->area = RectangleArea;
}

static Rectangle *RectangleCreate(int a, int b)
{
    Rectangle *rectangle = malloc(sizeof(Rectangle));
    RectangleInit(rectangle, a, b);
    return rectangle;
}

MRectangle mrectangle[1] =
{{
    RectangleCreate,
    RectangleInit,
}};

static int TriangleArea(Shape *shape)
{
    printf("Triangle class area\n");
    return (shape->width * shape->height) / 2;
}

static void TriangleInit(Triangle *this, int a, int b)
{
    mshape->init(this->shape, a, b);
    this->shape->area = TriangleArea;
}

static Triangle *TriangleCreate(int a, int b)
{
    Triangle *triangle = malloc(sizeof(Triangle));
    TriangleInit(triangle, a, b);
    return triangle;
}
struct MTriangle MTriangle[1] =
{{
    TriangleCreate,
    TriangleInit,
}};

int main(void)
{
    Shape *shape;
    Rectangle *rec;
    Triangle *tri;

    rec = mrectangle->create(10, 7);
    tri = MTriangle->create(10, 5);

    // 存储矩形的地址
    shape = rec->shape;
    // 调用矩形的求面积函数 area
    shape->area(shape);

    // 存储三角形的地址
    shape = tri->shape;
    // 调用三角形的求面积函数 area
    shape->area(shape);

    return 0;
}

